package gold.digger;

import gold.vo.ListNode;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC1019 {
    public long startExecuteTime = System.currentTimeMillis();

    /*
     * @param 此题目参考了别人代码
     * 这是因为问题情况较为复杂
     * 未来需要再次复习此道题目
     * 这个题目是典型的单调栈解法，以后需要多看看这类问题
     * @return:
     */
    class Solution {
        public int[] nextLargerNodes(ListNode head) {
            ListNode tail = reverse(head);
            Deque<Integer> stack = new LinkedList<>();
            int[] res = new int[tail.val];
            int index = tail.val - 1;
            tail = tail.next;
            while (index >= 0) {
                while (!stack.isEmpty() && tail.val >= stack.peek()) {
                    stack.poll();
                }
                res[index--] = stack.isEmpty() ? 0 : stack.peek();
                stack.push(tail.val);
                tail = tail.next;
            }
            return res;
        }

        private ListNode reverse(ListNode head) {
            //之所以返回dummy是为了用dummy.val保存链表的长度
            ListNode dummy = new ListNode(-1);
            int count = 0;
            ListNode cur = head, pre = null;
            while (cur != null) {
                ListNode temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;
                count++;
            }
            dummy.val = count;
            dummy.next = pre;
            return dummy;
        }
    }

    public void run() {
        Solution solution = new Solution();
        List<Integer> list = new ArrayList<>();
        System.out.println(solution.toString());
    }

    public static void main(String[] args) throws Exception {
        LC1019 an = new LC1019();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
